#include "crenderpass.h"

namespace NEngine {

// -- Clear color static const used for clearing the render target and shader target views
const float CRenderPass::clearcolor[4] = {0.0f, 0.0f, 0.0f, 0.0f};

// ------------------------------------------------------------------------------------------------
// Draw Iterate through the objects and draw them
// ------------------------------------------------------------------------------------------------
void CRenderPass::Draw() {
    Matrix4x4 view = (*rpref.view)->GetViewTransform();
    rpref.cb->view = view.Transpose4x4();

    ushort vtxoffset = 0;
    for(uint j = 0; j < rpref.objects->numindices.GetSize(); ++j) {
        const Matrix4x4& world = rpref.objects->wmats[j];
        rpref.cb->world = world.Transpose4x4();
        rpref.cb->tinvworld = world.InvTrans();
        rpref.cb->tinvworld = rpref.cb->tinvworld.Transpose4x4();

        // -- update matrix buffer per object and draw them
        (*rpref.ictx)->UpdateSubresource(*rpref.cbuffmats, 0, NULL, rpref.cb, 0,0);
        (*rpref.ictx)->Draw(rpref.objects->numverts[j], vtxoffset);

        // -- find the offset to the next set of vertices
        vtxoffset += rpref.objects->numverts[j];
    }
}

// ================================================================================================
// RenderPass method for public use
// ================================================================================================
void CRenderPass::RenderPass() {
    // -- set the shaders relevant to the pass we are interested in
    (*rpref.ictx)->VSSetShader(*rpref.vtxshader, NULL, 0);
    (*rpref.ictx)->PSSetShader(*rpref.psshader, NULL, 0);

    // -- clear the render target view and depth stencil view
    (*rpref.ictx)->ClearRenderTargetView(*rpref.rt, clearcolor);
    (*rpref.ictx)->ClearDepthStencilView(*rpref.dstencil, D3D11_CLEAR_DEPTH, 1.0f, 0);
    (*rpref.ictx)->OMSetRenderTargets(1, rpref.rt, *rpref.dstencil);

    (*rpref.ictx)->PSSetShaderResources(0, rpref.numsres, rpref.sres);

    // -- draw the scene
    Draw();

    // -- clear the shader resource
    ID3D11ShaderResourceView* nullsr = NULL;
    for(uint i = 0; i < rpref.numsres; ++i)
        (*rpref.ictx)->PSSetShaderResources(i, 1, &nullsr);
}

} // -- namespace NEngine